import React, { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
import { PermissionCode } from '../types/auth';

interface PermissionGuardProps {
  children: React.ReactNode;
  permission?: PermissionCode;
  permissions?: PermissionCode[];
  requireAll?: boolean;
  fallback?: React.ReactNode;
}

const PermissionGuard: React.FC<PermissionGuardProps> = ({
  children,
  permission,
  permissions,
  requireAll = false,
  fallback = <Navigate to="/admin/login" replace />
}) => {
  const { hasPermission, hasAnyPermission, hasAllPermissions, isSuperAdmin, userPermissions } = useAuth();
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    // 等待权限加载完成
    if (userPermissions.length > 0) {
      setIsChecking(false);
    }
  }, [userPermissions]);

  // 检查是否已登录
  const isAuthenticated = localStorage.getItem('adminToken') !== null;
  if (!isAuthenticated) {
    return <>{fallback}</>;
  }

  // 等待权限加载完成
  if (isChecking) {
    return null;
  }

  // 超级管理员拥有所有权限
  if (isSuperAdmin()) {
    return <>{children}</>;
  }

  // 检查单个权限
  if (permission) {
    if (!hasPermission(permission)) {
      return <Navigate to="/admin/dashboard" replace />;
    }
  }

  // 检查多个权限
  if (permissions) {
    const hasAccess = requireAll ? hasAllPermissions(permissions) : hasAnyPermission(permissions);
    if (!hasAccess) {
      return <Navigate to="/admin/dashboard" replace />;
    }
  }

  return <>{children}</>;
};

export default PermissionGuard; 